// Author: wsfuyibing <682805@qq.com>
// Date: 2025-06-24

package pay_offline

import (
	"context"
	"gitee.com/go-libs/db-xorm/db"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/errs"
	"server/app/http/logics/master/order"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/kind"
	"server/app/lib"
)

// Logic
// 订单详情.
type Logic struct {
	order.Logic
	arcade *models.Arcades

	affects int64
	orders  *models.Order

	request  *Request
	response *Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: &Response{},
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Json(i, o.request); err == nil {
		o.arcade, _ = lib.Arcade.GetMaster().GetArcade(i)
	}
	return
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		res = result.New()
	)

	if err := db.Transaction(ctx,
		o.RunCheck,
		o.RunPayKind,
		o.RunUpdate,
	); err != nil {
		return res.WithError(err)
	}

	return res.With(o.response)
}

func (o *Logic) RunCheck(ctx context.Context, sess *db.Session) (err error) {
	if o.orders, err = o.GetOrderByNo(ctx, sess, o.arcade.Id, o.request.OrderNo); err == nil {
		o.response.With(o.orders)
	}
	return
}

func (o *Logic) RunPayKind(ctx context.Context, sess *db.Session) (err error) {
	var kinds []*models.OrderPayKind
	if kinds, err = o.GetPayKinds(ctx, sess, o.orders.Id); err == nil {
		for _, k := range kinds {
			o.response.AddPayKind(k)
		}
	}
	return
}

func (o *Logic) RunUpdate(ctx context.Context, sess *db.Session) (err error) {
	if o.affects, err = services.NewOrderService(sess).Dao.UpdateFieldsById(ctx, map[string]any{
		"state": kind.OrderStateSucceed,
	}, o.orders.Id); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}
	if o.affects > 0 {

	}
	return
}
